import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

import Layout from '@/views/layout'
import Home from '@/views/layout/home'
import Cart from '@/views/layout/cart'
import Category from '@/views/layout/category'
import User from '@/views/layout/user'

const Login = () => import('@/views/login')
const Order = () => import('@/views/order')
const Detail = () => import('@/views/detail')
const Search = () => import('@/views/search')
const Pay = () => import('@/views/pay')
const List = () => import('@/views/search/list')
const Address = () => import('@/views/address/index.vue')
const EditAddress = () => import('@/views/address/editAddress.vue')

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  { path: '/search', component: Search },
  { path: '/detail/:id', component: Detail },
  { path: '/list', component: List },
  { path: '/order', component: Order },
  { path: '/pay', component: Pay },
  { path: '/address/:id?', component: Address },
  { path: '/editAddress/:id?', component: EditAddress },
  {
    path: '/',
    redirect: '/home',
    component: Layout,
    children: [
      { path: '/home', component: Home },
      { path: '/category', component: Category },
      { path: '/cart', component: Cart },
      { path: '/user', component: User }
    ]
  }, {
    path: '*', redirect: '/'
  }
]

const router = new VueRouter({
  routes
})

const authUrls = ['/pay', '/order']

router.beforeEach((to, from, next) => {
  if (!authUrls.includes(to.path)) {
    next()
    return
  }
  if (store.getters.token) {
    next()
  } else {
    next('/login')
  }
})

export default router
